<template>
  <div class="app-container search-list">
    <search-form :forms="formOptions.forms" v-watermark="{text: email,time:Date.now()}"
                 :submit-handler="handleSearch"
                 :size="formOptions.size"
                 :fuzzy="formOptions.fuzzy"
                 :inline="formOptions.inline"
                 :label-width="formOptions.labelWidth"
                 :item-width="formOptions.itemWidth"
                 :showSearchBtn="formOptions.showSearchBtn"
                 :showResetBtn="formOptions.showResetBtn"
                 :submitBtnText="formOptions.submitBtnText"
                 :resetBtnText="formOptions.resetBtnText"
                 :resetBtnCallback="formOptions.resetBtnCallback"></search-form>
    <div class="search-table-info">
      <div class="search-table-info-btns" style="display: flex;align-items: flex-start">
        <el-button  v-if="authFilter(siteLists)" type="primary" size="mini" @click="handleAdd()">新增商品
        </el-button>
        <el-button type="primary" size="mini" @click="tableHeadConfig()">编辑表头</el-button>
        <el-button type="primary" size="mini" @click="batchModifySettings()">批量设置</el-button>
        <el-button type="danger" size="mini" @click="handleDel">批量删除</el-button>
        <el-button type="primary" size="mini" @click="showPublishWarning()">批量上架</el-button>
        <el-button type="primary" size="mini" @click="showUnpublishWarning()">批量下架</el-button>
        <upload-file
            v-if="authFilter(siteLists)"
            :headers="headers"
            style="margin-left: 10px;margin-right: 10px"
            :fileType="['doc', 'pdf']"
            type="file"
            :drag="true"
            show-text="导入商品"
            :showFileList="true"
            accept=".xlsx"
            :isShowTip="true"
            :lazy="true"
            :responseFn="handleResponse"
            :action="uploadPath"
            title="选择文件"
            v-model="importProductsFileName"
        ></upload-file>
        <el-button v-if="authFilter(siteLists)"  type="primary" size="mini" @click="settingVisible = true" :loading="submitLoading">
          {{ submitLoading ? '导出中' : '导出商品' }}
        </el-button>
        <el-button  v-if="authFilter(siteLists)" type="default" size="mini" @click="handleDown()">商品导入模板下载</el-button>
        <el-button type="primary" size="mini" @click="settingFbVisible = true" :loading="submitLoading">
          {{ submitLoading ? '导出中' : '导出Facebook_feed' }}
        </el-button>
      </div>
    </div>
    <ag-grid style="background-color: #fff" v-watermark="{text: email,time:Date.now()}" data-id="myGrid"
             :tooltipShowDelay="0" :pageSizes="[50, 300, 600, 1000]" :pageSize="pageParams.pageSize"
             v-el-height-adaptive-table="adaptive" height="500px" :total="total" v-loading="loading"
             :columnDefs="columns" :defRowData="tableData" @delete="handleSingleDel" @select-changed="handleSelect"
             @current-change="handleCurrentChange" @size-change="handlePageSize"></ag-grid>
    <!--    <table-pagination
            size="small"
            style="position: relative;z-index: 9"
            ref="el-search-table"
            :fetch="getData"
            type="remote"
            :adaptive="fixOption"
            :page-sizes="[50, 100, 600]"
            :columns="columns"
            :form-options="formOptions"
            list-field="records"
            total-field="totalElements"
            page-index-key="page"
            page-size-key="pageSize"
            height="300"
            method="get"
            @selection-change="handleSelectionChange">
          <template slot="button">
            <el-button type="primary" size="mini" @click="tableHeadConfig()">编辑表头</el-button>
            <el-button type="primary" size="mini" @click="batchModifySettings()">批量设置</el-button>
            <el-button type="primary" size="mini" @click="showPublishWarning()">批量上架</el-button>
            <el-button type="primary" size="mini" @click="showUnpublishWarning()">批量下架</el-button>
          </template>
          <el-table-column label="SPU编码" slot="append" width="180px" fixed='left' align='left'
                           :show-overflow-tooltip="true">
            <template slot-scope="{row}">
              <span @click="handleDetail(row.id)" style="color: #409EFF">
                {{ row.spuCode }}
              </span>
            </template>
          </el-table-column>
          <el-table-column label="商品图片" slot="append" width="100px" fixed='left' align='left' Ω>
            <template slot-scope="{row}">
              <el-button type="text" size="mini">
                <el-image
                    style="width: 36px; height: 40px;"
                    v-img-host="{url: row.mainImage}"
                    :src="bgPic"
                    :preview-src-list="[row.mainImage]"
                    fit="contain"></el-image>
              </el-button>
            </template>
          </el-table-column>
          <template slot-scope="scope" slot="specifications">
            <span v-html="scope.row.specifications" style="font-size: 12px"></span>
          </template>
          <template slot-scope="scope" slot="operations">
            <el-link type="primary" @click="handlePreview(scope.row.id)">预览</el-link>
          </template>
        </table-pagination>-->
    <el-drawer
        size="400px"
        title="表头设置"
        :wrapperClosable="false"
        :visible.sync="tableHeaderDialogVisible">
      <el-form ref="tableHeaderConfigForm" :model="tableHeaderConfig" label-width="80px">
        <el-form-item label="选择表头" prop="tableList">
          <el-checkbox-group v-model="siteTableHeaderConfig" class="table-check-prop">
            <el-checkbox v-for="(header,key) in tableHeaders" :label="header.value" :key="key">{{ header.name }}
            </el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="saveTableHeaderConfig('tableHeaderConfigForm')" :loading="submitLoading">保存
          </el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
    <el-drawer
        size="400px"
        title="批量设置"
        :wrapperClosable="false"
        :visible.sync="dialogVisible"
        class="good-setting-panel">
      <el-tabs type="border-card" v-model="activeName">
        <el-tab-pane label="虚拟销量" name="virtualQtyForm">
          <el-form ref="virtualQtyForm" :model="virtualSalesQty" :rules="virtualQtyRules" label-width="120px">
            <el-form-item label="是否显示：" prop="showVirtualSaleQty">
              <el-radio-group v-model="virtualSalesQty.showVirtualSaleQty">
                <el-radio :label="0">不显示</el-radio>
                <el-radio :label="1">显示</el-radio>
              </el-radio-group>
            </el-form-item>
            <template v-if="!!virtualSalesQty.showVirtualSaleQty">
              <el-form-item label="销量公式：" prop="virtualSaleQtyMethod">
                <el-select v-model="virtualSalesQty.virtualSaleQtyMethod" clearable placeholder="请选择"
                           @change="changeVirtualQtyFormula">
                  <el-option value="FIX_VALUE" label="固定销量"></el-option>
                  <el-option value="ADD_FIX_VALUE" label="增加固定销量"></el-option>
                  <el-option value="ADD_PERCENT_VALUE" label="增加比例销量"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="销量公式值：" prop="virtualSaleQtyValue">
                <el-input v-model="virtualSalesQty.virtualSaleQtyValue" placeholder="请输入值" style="width: 193px"/>
              </el-form-item>
              <el-form-item label="固定公式单位：" prop="unit">
                <span style="padding-left: 10px">{{ virtualSalesQty.unit }}</span>
              </el-form-item>
            </template>
            <el-form-item>
              <el-button type="primary" @click="batchModifyVirtualSaleQty('virtualQtyForm')" :loading="submitLoading">
                保存
              </el-button>
              <el-button @click="handleReset('virtualQtyForm')">取消</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="销售价" name="sellPriceForm">
          <el-form ref="sellPriceForm" :model="sellPrice" :rules="sellPriceRules" label-width="120px">
            <template>
              <el-form-item label="价格公式：" prop="sellPriceMethod">
                <el-select v-model="sellPrice.sellPriceMethod" clearable placeholder="请选择"
                           @change="changeSellPriceFormula">
                  <el-option value="ADD_FIX_VALUE" label="增加固定金额"></el-option>
                  <el-option value="ADD_PERCENT_VALUE" label="增加比例金额"></el-option>
                  <el-option value="REDUCE_FIX_VALUE" label="减少固定金额"></el-option>
                  <el-option value="REDUCE_PERCENT_VALUE" label="减少比例金额"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="价格公式值：" prop="sellPriceValue">
                <el-input v-model="sellPrice.sellPriceValue" placeholder="请输入值" style="width: 193px"/>
              </el-form-item>
              <el-form-item label="价格公式单位：" prop="unit">
                <span style="padding-left: 10px">{{ sellPrice.unit }}</span>
              </el-form-item>
            </template>
            <el-form-item>
              <el-button type="primary" @click="batchModifySellPrice('sellPriceForm')"
                         :loading="submitLoading">保存
              </el-button>
              <el-button @click="handleReset('sellPriceForm')">取消</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>

        <el-tab-pane label="虚拟价" name="virtualPriceForm">
          <el-form ref="virtualPriceForm" :model="virtualSalesPrice" :rules="virtualPriceRules" label-width="120px">
            <template>
              <el-form-item label="价格公式：" prop="virtualSalePriceMethod">
                <el-select v-model="virtualSalesPrice.virtualSalePriceMethod" clearable placeholder="请选择"
                           @change="changeVirtualPriceFormula">
                  <el-option value="FIX_VALUE" label="固定金额"></el-option>
                  <el-option value="EQUAL_SELL_PRICE" label="等于销售价"></el-option>
                  <el-option value="ADD_FIX_VALUE" label="增加固定金额(在原虚拟价基础上)"></el-option>
                  <el-option value="ADD_PERCENT_VALUE" label="增加比例价格(在原虚拟价基础上)"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="价格公式值：" prop="virtualSalePriceValue"
                            v-if="virtualSalesPrice.virtualSalePriceMethod!=='EQUAL_SELL_PRICE'">
                <el-input v-model="virtualSalesPrice.virtualSalePriceValue" placeholder="请输入值"
                          style="width: 193px"/>
              </el-form-item>
              <el-form-item label="价格公式单位：" prop="unit">
                <span style="padding-left: 10px">{{ virtualSalesPrice.unit }}</span>
              </el-form-item>
            </template>
            <el-form-item>
              <el-button type="primary" @click="batchModifyVirtualSalePrice('virtualPriceForm')"
                         :loading="submitLoading">保存
              </el-button>
              <el-button @click="handleReset('virtualPriceForm')">取消</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="商品标签" name="spuTagsForm">
          <el-form ref="spuTagsForm" :model="spuTags" label-width="120px">
            <el-form-item label="商品标签：">
              <div class="good-tags">
                <el-tag
                    class="good-tags-item"
                    :key="index"
                    v-for="(tag, index) in spuTags.tagList"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(index)">
                  {{ tag.label }}
                </el-tag>
                <el-input
                    class="input-new-tag"
                    v-if="inputVisible"
                    v-model="inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm"
                    @blur="handleInputConfirm"
                >
                </el-input>
                <el-button v-else class="button-new-tag" icon="el-icon-plus" size="small" @click="showInput">新增标签
                </el-button>
              </div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="batchModifySpuTags('spuTagsForm')" :loading="submitLoading">保存
              </el-button>
              <el-button @click="handleReset('spuTagsForm')">取消</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </el-drawer>
    <el-dialog :visible.sync="settingVisible" title="商品导出" width="400px">
      <div class="desc">
        <div class="export" style="text-align: left;">
          <section>
            <div class="orca-row orca-form-item">
              <el-radio v-model="exportType" label="all" style="margin-bottom: 15px">所有商品</el-radio>
              <el-radio v-model="exportType" label="filter">当前选择的商品</el-radio>
            </div>
          </section>
        </div>
        <div style="margin-top: 20px">
          <el-button type="primary" @click="handleExport('goods')" :loading="submitLoading">
            {{ submitLoading ? '导出中' : '导出' }}
          </el-button>
          <el-button @click="settingVisible = false">取消</el-button>
        </div>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="settingFbVisible" title="Facebook_feed" width="400px">
      <div class="desc">
        <div class="export" style="text-align: left;">
          <section>
            <div class="orca-row orca-form-item">
              <el-radio v-model="exportType" label="all" style="margin-bottom: 15px">所有商品</el-radio>
              <el-radio v-model="exportType" label="filter">当前选择的商品</el-radio>
            </div>
          </section>
        </div>
        <div style="margin-top: 20px">
          <el-button type="primary" @click="handleExport('facebook')" :loading="submitLoading">
            {{ submitLoading ? '导出中' : '导出' }}
          </el-button>
          <el-button @click="settingFbVisible = false">取消</el-button>
        </div>
      </div>
    </el-dialog>
    <!--    <el-dialog :visible.sync="importProductsVisible" width="410px" style="height: 490px;" title="商品导入">-->
    <!--      <upload-file-->
    <!--          :headers="headers"-->
    <!--          :fileType="['doc', 'pdf']"-->
    <!--          type="file"-->
    <!--          :drag="true"-->
    <!--          :showFileList="true"-->
    <!--          accept=".xlsx"-->
    <!--          :isShowTip="true"-->
    <!--          :lazy="true"-->
    <!--          :responseFn="handleResponse"-->
    <!--          :action="uploadPath"-->
    <!--          show-text="选择文件"-->
    <!--          title="选择文件"-->
    <!--          v-model="importProductsFileName"-->
    <!--      ></upload-file>-->
    <!--      <div class="import_info">-->
    <!--        <p style="color: #30354d;font-size: 14px;line-height: 20px;">请按规范填写表格，仅支持 xlsx 格式文件</p>-->
    <!--        &lt;!&ndash;        <p>上传的文件不能超过 10 M</p>&ndash;&gt;-->
    <!--      </div>-->
    <!--      <div slot="footer" class="dialog-footer">-->
    <!--        <el-button type="primary" @click="handleFileName()">确定</el-button>-->
    <!--      </div>-->
    <!--    </el-dialog>-->
  </div>
</template>

<script>
import {getToken} from '@/utils/auth';
import uploadFile from '@/components/Upload/uploadFile';
import AgGrid from '_c/AgGrid';
import elHeightAdaptiveTable from '@/directives/el-table';
import bgPic from '@/assets/images/bg-grey.png';
import searchForm from '_c/Tables/search-form';
import previewRenderer from './components/preview';
import imageRenderer from './components/image';
import tooltipRenderer from './components/tooltip';
import textRenderer from './components/text';
import linkRenderer from './components/link';
import dateRenderer from './components/date';
import CustomHeader from './components/CustomHeader.vue';
import Currency from './components/currency';
import {
    getSpuPage, getSpuTagList, getSeriesList, updateSpuPublish,
    batchModifyVirtualSalesQty, batchModifySellPrice, batchModifyVirtualSalesPrice, batchModifySpuTags, batchDelGoods
} from '@/api/goods';
import {addTableHeaderConfig, getTableHeaderConfig} from '@/api/site-config';

import {debounce, parseTime} from '@/utils/utils';
import {currency} from '@/utils/filters';
import {mapGetters} from 'vuex';
import axios from 'axios';

const columns = [
    {
        type: 'selection',
        width: 60,
        headerCheckboxSelection: true,
        headerCheckboxSelectionFilteredOnly: true,
        checkboxSelection: true,
        lockPosition: true,
        initialPinned: 'left'
    },
    {
        headerName: 'SPU编码',
        field: 'spuCode',
        width: 160,
        resizable: true,
        initialPinned: 'left',
        lockPosition: true,
        cellRendererFramework: 'linkRenderer'
    },
    {
        headerName: '商品图片',
        field: 'mainImage',
        initialPinned: 'left',
        lockPosition: true,
        width: 100,
        autoHeight: true,
        cellRendererFramework: 'imageRenderer'
    },
    {
        headerName: '商品名称',
        field: 'spuName',
        tooltipField: 'spuName',
        lockPosition: true,
        resizable: true,
        tooltipComponent: 'tooltipRenderer'
    },
    {
        headerName: '商品类型',
        field: 'spuType',
        tooltipField: 'spuType',
        lockPosition: true,
        cellRenderer: row => {
            let published = row.value;
            if (published === '0') {
                return '普通商品';
            } else if (published === '1') {
                return '定制商品';
            }
        }
    },
    {
        headerName: '销售价',
        field: 'sellPrice',
        lockPosition: true,
        sortable: true,
        headerComponentFramework: 'CustomHeader',
        cellRendererFramework: 'Currency'
    // renderHeader (h, {column, $index}) {
    //     return [
    //         column.label,
    //         h(
    //             'el-tooltip',
    //             {
    //                 props: {
    //                     content: (function () {
    //                         return '当商品参与限时促销活动时，商品售价将无法修改';
    //                     })(),
    //                     placement: 'top'
    //                 }
    //             },
    //             [
    //                 h('span', {
    //                     class: {
    //                         'el-icon-question': true
    //                     }
    //                 })
    //             ]
    //         )
    //     ];
    // }
    },
    {
        headerName: '虚拟价(原价)',
        field: 'virtualSellPrice',
        sortable: true,
        headerComponentFramework: 'CustomHeader',
        lockPosition: true,
        cellRendererFramework: 'Currency'
    },
    {
        headerName: '销售量',
        field: 'salesQty',
        lockPosition: true,
        sortable: true,
        headerComponentFramework: 'CustomHeader'
    },
    {
        headerName: '虚拟销量',
        field: 'virtualSalesQty',
        sortable: true,
        headerComponentFramework: 'CustomHeader'
    },
    {
        headerName: '上架时间',
        field: 'publishTime',
        sortable: true,
        headerComponentFramework: 'CustomHeader',
        cellRendererFramework: 'dateRenderer'
    },
    {
        headerName: '上架状态',
        field: 'published',
        lockPosition: true,
        cellRenderer: row => {
            let published = row.value;
            if (published === 1) {
                return '上架';
            } else if (published === -1) {
                return '未上架';
            } else {
                return '下架';
            }
        }
    },
    {headerName: '商品标签', field: 'spuTags', lockPosition: true},
    {headerName: '商品系列', field: 'spuSeries', lockPosition: true},
    {
        headerName: '商品规格',
        field: 'specifications',
        cellRendererFramework: 'textRenderer',
        width: 300,
        lockPosition: true,
        wrapText: true
    // autoHeight: true
    },
    {headerName: '供应商', field: 'spuVendor', resizable: true},
    {
        headerName: '重量',
        field: 'weight',
        lockPosition: true,
        sortable: true,
        headerComponentFramework: 'CustomHeader',
        cellRenderer: row => {
            if (row.value) {
                return row.value + 'g';
            }
        }
    },
    {
        headerName: '操作',
        lockPosition: true,
        width: 100,
        cellRendererFramework: 'previewRenderer',
        initialPinned: 'left'
    }
];

export default {
    name: 'goods-list',
    // eslint-disable-next-line vue/no-unused-components
    components: {uploadFile, searchForm, AgGrid, previewRenderer, imageRenderer, tooltipRenderer, textRenderer, linkRenderer, CustomHeader, dateRenderer, Currency},
    directives: {
        elHeightAdaptiveTable
    },
    data () {
        const checkNumber = (rule, value, callback) => {
            let num = /^(0|[1-9]\d*)(\s|$|\.\d{1,2}\b)/;
            value = '' + value;
            if (isNaN(value) || !(num.test(value))) {
                callback(new Error('请输入大于0的数,且最多两位小数'));
            } else {
                callback();
            }
        };
        return {
            exportType: 'all',
            settingFbVisible: false,
            settingVisible: false,
            importProductsVisible: false,
            headers: {'X-TULIANG-Session-Token': getToken()},
            importProductsFileName: '',
            adaptive: {
                fixedHeader: true,
                bottomOffset: 60,
                id: 'myGrid'
            },
            loading: false,
            total: 0,
            tableData: [],
            bgPic,
            siteDomain: '',
            fixOption: {fixedHeader: true},
            pageParams: {
                page: 1,
                pageSize: 50,
                spuCode: '',
                spuName: '',
                spuTags: [],
                spuSeries: [],
                published: null,
                startTimePublish: '',
                endTimePublish: '',
                sortField: 'createDate',
                sortType: 'DESC',
                sellPriceMin: undefined,
                sellPriceMax: undefined

            },
            formOptions: {
                showResetBtn: true,
                showSearchBtn: true,
                inline: false,
                labelWidth: 120,
                submitBtnText: '查询',
                size: 'small',
                resetBtnCallback: () => {
                    this.pageParams = {
                        page: 1,
                        pageSize: 50,
                        spuCode: '',
                        spuName: '',
                        spuTags: [],
                        spuSeries: [],
                        published: null,
                        startTimePublish: '',
                        endTimePublish: '',
                        sortField: 'createDate',
                        sortType: 'DESC',
                        sellPriceMin: undefined,
                        sellPriceMax: undefined
                    };
                    this.getData(this.pageParams);
                },
                forms: [
                    {prop: 'spuCode', label: 'SPU：', placeholder: '请输入SPU'},
                    {prop: 'spuName', label: '商品名称：', placeholder: '请输入商品名称'},
                    {
                        prop: 'spuType',
                        label: '商品类型',
                        itemType: 'select',
                        options: [
                            {label: '全部商品', value: ''},
                            {label: '普通商品', value: 0},
                            {label: '定制', value: 1}
                        ]
                    },
                    {
                        prop: 'spuTags',
                        label: '产品标签：',
                        itemType: 'select',
                        placeholder: '请选择产品标签',
                        multiple: true,
                        filterable: true,
                        loading: false,
                        remoteMethod: debounce((query) => {
                            if (query !== '') {
                                this.formOptions.forms[3].loading = true;
                                this.loadingSpuTagList(query).then(res => {
                                    this.formOptions.forms[3].options = res;
                                    this.formOptions.forms[3].loading = false;
                                });
                            }
                        }, 300)
                    },
                    {
                        prop: 'spuSeries',
                        label: '产品系列：',
                        itemType: 'select',
                        placeholder: '请选择产品系列',
                        multiple: true,
                        selectFetch: () => {
                            return new Promise((resolve, reject) => {
                                this.$nextTick(() => {
                                    let siteId = this.siteId;
                                    getSeriesList({'siteId': siteId}).then(res => {
                                        let records = res.data;
                                        if (records == null || records.length <= 0) {
                                            this.seriesList = [];
                                        }
                                        let tempList = [];
                                        records.forEach(item => {
                                            tempList.push({'label': item.label, 'value': item.value});
                                        });
                                        resolve(tempList);
                                    });
                                });
                            });
                        }
                    },
                    {
                        prop: 'published',
                        label: '上架状态：',
                        itemType: 'select',
                        placeholder: '请选择上架状态',
                        options: [
                            {label: '上架', value: 1},
                            {label: '下架', value: 0},
                            {label: '未上架', value: -1}
                        ]
                    },
                    {
                        prop: ['startTimePublish', 'endTimePublish'],
                        label: '上架时间：',
                        itemType: 'daterange',
                        startPlaceholder: ' 开始日期',
                        endPlaceholder: ' 结束日期'
                    },
                    {
                        prop: ['sellPriceMin', 'sellPriceMax'],
                        label: '销售价：',
                        itemType: 'rangePrice',
                        startPlaceholder: '最低金额',
                        endPlaceholder: '最高金额'
                    }
                ]
            },
            columns: [],
            selectedList: [],
            selectedIdList: [],
            submitLoading: false,
            dialogVisible: false,
            tableHeaderDialogVisible: false,
            tableHeaderConfig: {
                headers: '',
                tableName: 'goods-list'
            },
            siteTableHeaderConfig: [],
            tableHeaders: [
                {value: 'spuName', name: '商品名称'},
                {value: 'spuType', name: '商品类型'},
                {value: 'sellPrice', name: '销售价'},
                {value: 'virtualSellPrice', name: '虚拟价(原价)'},
                {value: 'salesQty', name: '销售量'},
                {value: 'virtualSalesQty', name: '虚拟销量'},
                {value: 'publishTime', name: '上架时间'},
                {value: 'published', name: '上架状态'},
                {value: 'spuTags', name: '商品标签'},
                {value: 'spuSeries', name: '商品系列'},
                {value: 'specifications', name: '商品规格'},
                {value: 'spuVendor', name: '供应商'},
                {value: 'weight', name: '重量'}
            ],
            spuTags: {
                tagList: [],
                selectedTagList: []
            },
            seriesList: [],
            activeName: 'virtualQtyForm',
            virtualQtyRules: {
                showVirtualSaleQty: [
                    {required: true, message: '请选择', trigger: 'blur'}
                ],
                virtualSaleQtyMethod: [
                    {required: true, message: '请选择公式', trigger: 'blur'}
                ],
                virtualSaleQtyValue: [
                    {required: true, message: '请填写', trigger: 'blur'},
                    {validator: checkNumber, trigger: 'blur'}
                ]
            },
            sellPriceRules: {
                sellPriceMethod: [
                    {required: true, message: '请选择公式', trigger: 'blur'}
                ],
                sellPriceValue: [
                    {required: true, message: '请填写', trigger: 'blur'},
                    {validator: checkNumber, trigger: 'blur'}
                ]
            },
            virtualPriceRules: {
                virtualSalePriceMethod: [
                    {required: true, message: '请选择公式', trigger: 'blur'}
                ],
                virtualSalePriceValue: [
                    // {required: true, message: '请填写', trigger: 'blur'},
                    {validator: checkNumber, trigger: 'blur'}
                ]
            },
            virtualSalesQty: {
                showVirtualSaleQty: 0,
                siteId: this.siteId,
                unit: '个'
            },
            sellPrice: {
                siteId: this.siteId,
                unit: '$'
            },
            virtualSalesPrice: {
                siteId: this.siteId,
                unit: '$'
            },
            inputVisible: false,
            inputValue: '',
            formParams: {
                ids: []
            },
            siteLists: [23, 6]
        };
    },
    computed: {
        ...mapGetters(['siteList', 'tableHeight', 'sort', 'timeZone', 'delId', 'email']),
        siteId () {
            return this.$store.state.user.siteId;
        },
        siteInfo () {
            let info = this.siteList.find(res => res.id === Number(this.siteId));
            return info;
        },
        uploadPath () {
            return process.env.VUE_APP_BASE_API + '/spu/import?siteId=' + this.siteId;
        },
        exportPath () {
            return `${process.env.VUE_APP_BASE_API}/spu/export`;
        },
        exportFbFeedPath () {
            return `${process.env.VUE_APP_BASE_API}/spu/export-fb-feed`;
        }
    },
    watch: {
        sort: {
            immediate: false,
            deep: true,
            handler (val) {
                const key = this.tableHeaders.find(s => s.name === val.name).value;
                this.pageParams.sortField = key;
                this.pageParams.sortType = val.key.toUpperCase();
                this.getData(this.pageParams);
            }
        },
        delId: {
            immediate: false,
            deep: true,
            handler (val) {
                this.handleSingleDel(val);
            }
        }
    },
    mounted () {
        this.getTableHeaderConfig();
        this.getData(this.pageParams);
    },
    methods: {
        authFilter (siteList) {
            return siteList.includes(this.siteId);
        },
        getTableHeaderConfig () {
            getTableHeaderConfig({'siteId': this.siteId, 'tableName': 'goods-list'}).then(res => {
                if (res.data) {
                    this.siteTableHeaderConfig = res.data.headers.split(',');
                    if (this.siteTableHeaderConfig.length !== 0) {
                        this.columns = columns.filter(column => {
                            if (column.type === 'selection' || column.headerName === '操作') {
                                return column;
                            }
                            return this.siteTableHeaderConfig.includes(column.field) || column.field === 'spuCode' || column.field === 'mainImage';
                        });
                        // this.$nextTick(() => {
                        //     this.$refs['el-search-table'].doLayout();
                        // });
                    }
                } else {
                    this.columns = columns;
                }
            });
        },
        getSiteTimeZoneTime (time, type) {
            if (time === undefined || time == null || time === '') {
                return time;
            }
            let tempTime = new Date(time);
            let month = (tempTime.getMonth() + 1 + 100).toString().substr(1);
            let date = (tempTime.getDate() + 100).toString().substr(1);
            const s = type === 'start' ? ' 00:00:00 UTC' : ' 23:59:59 UTC';
            let timeZoneStr = [tempTime.getFullYear(), month, date].join('/') + s + this.timeZone;
            console.log(timeZoneStr);
            return new Date(timeZoneStr).getTime();
        },
        saveTableHeaderConfig () {
            if (this.siteTableHeaderConfig.length === 0) {
                this.$message.error('请选择需要显示的表头!');
                return;
            }
            this.submitLoading = true;
            this.tableHeaderConfig.headers = this.siteTableHeaderConfig.join(',');
            this.tableHeaderConfig.siteId = this.siteId;
            addTableHeaderConfig(this.tableHeaderConfig).then(res => {
                this.submitLoading = false;
                this.tableHeaderDialogVisible = false;
                this.getTableHeaderConfig();
            }).catch(() => {
                this.submitLoading = false;
            });
        },
        isInteger (value) {
            let num = /^\+?[1-9][0-9]*$/;
            value = '' + value;
            if (isNaN(value) || !(num.test(value))) {
                return false;
            }
            return true;
        },
        loadingSpuTagList (name) {
            return new Promise(resolve => {
                let siteId = this.siteId;
                getSpuTagList({'siteId': siteId, name}).then((res) => {
                    this.spuTags.tagList = res.data;
                    resolve(res.data);
                });
            });
        },
        getData (params) {
            this.loading = true;
            this.pageParams.pageSize = params.pageSize;
            this.pageParams.page = params.page;
            let parameters = {
                siteId: this.siteId,
                spuTags: params.spuTags.join(','),
                spuSeries: params.spuSeries.join(',')
            };
            getSpuPage({...params, ...parameters}).then((res) => {
                let records = res.records;
                this.loading = false;
                if (records == null || records.length === 0) {
                    this.tableData = [];
                    this.total = 0;
                    return false;
                }
                records.forEach(record => {
                    let specifications = record.specifications;
                    if (specifications !== undefined && specifications != null && specifications !== '') {
                        record.specifications = specifications.replace(';', '<br/>');
                    }
                });
                res.records = records;
                this.tableData = res.records;
                this.total = res.totalElements;
            });
        },
        handleSearch (val) {
            if (val.sellPriceMin > val.sellPriceMax) {
                return this.$message.error('最低金额不能大于最高金额');
            }
            val.startTimePublish = this.getSiteTimeZoneTime(val.startTimePublish, 'start');
            val.endTimePublish = this.getSiteTimeZoneTime(val.endTimePublish, 'end');
            this.pageParams = Object.assign(this.pageParams, val);
            this.pageParams.page = 1;
            this.getData(this.pageParams);
        },
        handleAdd () {
            this.$router.push({name: 'goods-add'});
        },
        handleDetail (id) {
            this.$router.push({name: 'goods-detail', params: {id}});
        },
        batchModifySettings () {
            // 批量设置
            if (this.selectedIdList == null || this.selectedIdList.length <= 0) {
                this.$message.error('请先选择需要批量处理的商品！');
                return false;
            }
            this.dialogVisible = true;
        },
        showPublishWarning () {
            if (!this.selectedIdList.length) {
                this.$confirm('您确认要将站点所有商品批量上架吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.batchPublishSpu(true);
                });
            } else {
                this.$confirm('您确认要上架选中的这些商品吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.batchPublishSpu(true);
                });
            }
        },
        showUnpublishWarning () {
            if (!this.selectedIdList.length) {
                this.$confirm('您确认要将站点所有商品批量下架吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.batchPublishSpu(false);
                });
            } else {
                this.$confirm('您确认要下架选中的这些商品吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.batchPublishSpu(false);
                });
            }
        },
        batchPublishSpu (published) {
            let data = {
                siteId: this.siteId,
                spuIdList: this.selectedIdList,
                publishStatus: published ? 1 : 0
            };
            updateSpuPublish(data).then(res => {
                this.getData(this.pageParams);
                this.selectedIdList = [];
            });
        },
        handleSelectionChange (records) {
            if (records && records.length > 0) {
                let tempIdList = [];
                records.forEach(item => {
                    tempIdList.push(item.id);
                });
                this.selectedIdList = tempIdList;
                this.selectedList = records;
            } else {
                this.selectedIdList = [];
                this.selectedList = [];
            }
        },
        handleSingleDel (val) {
            this.delGoodsApi(val + '');
        },
        delGoodsApi (data) {
            this.$confirm('确认删除?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                batchDelGoods({siteId: this.siteId, ids: data}).then(res => {
                    this.$message.success('删除成功');
                    this.pageParams.page = 1;
                    this.getData(this.pageParams);
                });
            });
        },
        // 批量删除
        handleDel () {
            if (this.selectedIdList == null || this.selectedIdList.length <= 0) {
                this.$message.error('请先选择需要批量处理的商品！');
                return false;
            }
            this.delGoodsApi(this.selectedIdList.join(','));
        },
        handleReset (name) {
            this.$refs[name].resetFields();
            this.dialogVisible = false;
        },
        changeTabs (e) {
            this.$refs[e.name].resetFields();
            if (e.name === 'spuTagsForm') {
                let params = {'siteId': this.siteId, 'spuIds': this.selectedIdList.join(',')};
                getSpuTagList(params).then((res) => {
                    let templist = [];
                    if (res.data != null && res.data.length > 0) {
                        res.data.forEach(item => {
                            templist.push(item.value);
                        });
                    }
                    this.spuTags.selectedTagList = templist;
                });
            }
        },
        batchModifyVirtualSaleQty (name) {
            this.$refs[name].validate(valid => {
                if (!valid) {
                    this.$message.error('请正确填写！');
                } else {
                    let data = {
                        'siteId': this.siteId,
                        'spuIdList': this.selectedIdList,
                        'showVirtualSaleQty': this.virtualSalesQty.showVirtualSaleQty
                    };
                    if (this.virtualSalesQty.showVirtualSaleQty === 1) {
                        let virtualSaleValue = this.virtualSalesQty.virtualSaleQtyValue;
                        let virtualSaleMethod = this.virtualSalesQty.virtualSaleQtyMethod;
                        if (virtualSaleMethod !== 'ADD_PERCENT_VALUE' && !this.isInteger(virtualSaleValue)) {
                            this.$message.error('请填写有效的正整数');
                        }
                        data['virtualSaleValue'] = virtualSaleValue;
                        data['virtualSaleMethod'] = virtualSaleMethod;
                    }
                    this.submitLoading = true;
                    batchModifyVirtualSalesQty(data).then(res => {
                        this.selectedIdList = [];
                        this.handleReset(name);
                        this.getData(this.pageParams);
                        this.submitLoading = false;
                    }).catch(() => {
                        this.submitLoading = false;
                    });
                }
            });
        },
        batchModifySellPrice (name) {
            this.$refs[name].validate(valid => {
                if (!valid) {
                    this.$message.error('请正确填写！');
                } else {
                    let sellPriceMethod = this.sellPrice.sellPriceMethod;
                    let sellPriceValue = this.sellPrice.sellPriceValue;
                    if (sellPriceMethod === 'ADD_FIX_VALUE' || sellPriceMethod === 'REDUCE_FIX_VALUE') {
                        sellPriceValue = Math.floor(parseFloat(sellPriceValue) * 100).toString(); // 美元到美分的转换
                    }
                    let data = {
                        'siteId': this.siteId,
                        'spuIdList': this.selectedIdList,
                        'sellPriceMethod': sellPriceMethod,
                        'sellPriceValue': sellPriceValue
                    };
                    this.submitLoading = true;
                    batchModifySellPrice(data).then(res => {
                        this.selectedIdList = [];
                        this.handleReset(name);
                        this.getData(this.pageParams);
                        this.submitLoading = false;
                    }).catch(() => {
                        this.submitLoading = false;
                    });
                }
            });
        },
        batchModifyVirtualSalePrice (name) {
            this.$refs[name].validate(valid => {
                if (!valid) {
                    this.$message.error('请正确填写！');
                } else {
                    let virtualSaleMethod = this.virtualSalesPrice.virtualSalePriceMethod;
                    let virtualSaleValue = this.virtualSalesPrice.virtualSalePriceValue;
                    if (virtualSaleMethod !== 'ADD_PERCENT_VALUE' && virtualSaleMethod !== 'EQUAL_SELL_PRICE') {
                        virtualSaleValue = Math.floor(parseFloat(virtualSaleValue) * 100).toString(); // 美元到美分的转换
                    }
                    let data = {
                        'siteId': this.siteId,
                        'spuIdList': this.selectedIdList,
                        'virtualSaleMethod': virtualSaleMethod,
                        'virtualSaleValue': virtualSaleValue
                    };
                    this.submitLoading = true;
                    batchModifyVirtualSalesPrice(data).then(res => {
                        this.selectedIdList = [];
                        this.handleReset(name);
                        this.getData(this.pageParams);
                        this.submitLoading = false;
                    }).catch(() => {
                        this.submitLoading = false;
                    });
                }
            });
        },
        batchModifySpuTags (name) {
            let data = {
                'siteId': this.siteId,
                'spuIdList': this.selectedIdList,
                'spuTagList': this.spuTags.tagList.map(res => res.label)
            };
            this.submitLoading = true;
            batchModifySpuTags(data).then(res => {
                this.selectedIdList = [];
                this.handleReset(name);
                this.getData(this.pageParams);
                this.submitLoading = false;
            }).catch(() => {
                this.submitLoading = false;
            });
        },
        changeSellPriceFormula (data) {
            if (data === 'ADD_PERCENT_VALUE' || data === 'REDUCE_PERCENT_VALUE') {
                this.sellPrice.unit = '%';
            } else {
                this.sellPrice.unit = '$';
            }
        },
        changeVirtualPriceFormula (data) {
            if (data === 'ADD_PERCENT_VALUE') {
                this.virtualSalesPrice.unit = '%';
            } else {
                this.virtualSalesPrice.unit = '$';
            }
        },
        changeVirtualQtyFormula (data) {
            if (data === 'ADD_PERCENT_VALUE') {
                this.virtualSalesQty.unit = '%';
            } else {
                this.virtualSalesQty.unit = '个';
            }
        },
        handleClose (index) {
            this.spuTags.tagList.splice(index, 1);
        },
        showInput () {
            this.inputVisible = true;
            this.$nextTick(_ => {
                this.$refs.saveTagInput.$refs.input.focus();
            });
        },
        handleInputConfirm () {
            let inputValue = this.inputValue;
            if (inputValue) {
                this.spuTags.tagList.push({label: inputValue, value: inputValue});
            }
            this.inputVisible = false;
            this.inputValue = '';
        },
        handlePreview (id) {
            let url = 'https://' + this.siteInfo.domainName + '/goods/' + id;
            window.open(url, '_blank');
        },
        // 编辑表头
        tableHeadConfig () {
            this.tableHeaderDialogVisible = true;
        },
        handleCurrentChange (val) {
            this.selectedIdList = [];
            this.pageParams.page = val;
            this.getData(this.pageParams);
        },
        handlePageSize (val) {
            this.selectedIdList = [];
            this.pageParams.pageSize = val;
            this.getData(this.pageParams);
        },
        handleSelect (val) {
            this.selectedIdList = val;
        },
        handleImportProducts () {
            this.importProductsVisible = true;
        },
        handleResponse (response, file, fileList) {
            this.pageParams.page = 1;
            this.getData(this.pageParams);
            return response;
        },
        handleDown (data) {
            const link = document.createElement('a');
            link.href = 'https://cdn.shoplus.top/%E5%95%86%E5%93%81%E5%AF%BC%E5%85%A5%E6%A8%A1%E6%9D%BF.xlsx';
            link.download = 'shopplus商品导入模板.xlsx';
            link.style.display = 'none';
            document.body.appendChild(link);
            link.click();
            URL.revokeObjectURL(link.href);
            document.body.removeChild(link);
        },
        downloadURL (data, type) {
            const blob = new Blob([data], {type: 'application/vnd.ms-excel'});
            console.log(blob);
            const link = document.createElement('a');
            link.href = URL.createObjectURL(blob);
            link.download = `${type === 'goods' ? '商品列表' : 'facebook_feed'}` + '_' + this.siteId + '_' + new Date().getTime().toString() + (Math.random().toFixed(2) * 400 + 100).toString() + '.xlsx';
            link.style.display = 'none';
            document.body.appendChild(link);
            link.click();
            URL.revokeObjectURL(link.href);
            document.body.removeChild(link);
        },
        handleExport (type = 'goods') {
            let params = {siteId: this.siteId};
            if (this.exportType === 'filter' && (this.selectedIdList == null || this.selectedIdList.length <= 0)) {
                this.$message.error('请先选择需要批量导出的商品！');
                return false;
            }
            this.submitLoading = true;
            params = this.exportType === 'all' ? params : Object.assign(params, {ids: this.selectedIdList.join(',')});
            console.log(type);
            axios({
                method: 'get',
                params,
                url: type === 'goods' ? this.exportPath : this.exportFbFeedPath,
                headers: {
                    'X-TULIANG-Session-Token': getToken()
                },
                responseType: 'arraybuffer'
            }).then(res => {
                this.downloadURL(res.data, type);
                this.submitLoading = false;
            }).catch(() => {
                this.$message.error('导出失败！');
                this.submitLoading = false;
            });
        }
    }
};
</script>

<style scoped lang="scss">
.search-table-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 64px;
  background: #fff;
  margin-top: 12px;
  padding: 10px 34px 10px;
}

.search-list {
  h4 {
    border-bottom: 1px solid #E8E8E8;
    margin: 0;
    margin-bottom: 10px;
    padding-bottom: 10px;
  }
}
</style>

<style lang="scss">
.good-setting-panel {
  .el-tabs--border-card {
    box-shadow: none;
  }
}

.table-check-prop {
  display: flex;
  align-items: center;
  flex-wrap: wrap;

  .el-checkbox {
    width: 50%;
    margin: 0;
  }
}
</style>
